<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleSetLineChartData('paper')">
          <div class="card-panel-icon-wrapper icon-people">
            <el-icon class="card-panel-icon" :size="45">
              <DocumentCopy />
            </el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">试卷总数</div>
            <div class="card-panel-num">{{ animatedStatistics.paperCount }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleSetLineChartData('question')">
          <div class="card-panel-icon-wrapper icon-message">
            <el-icon class="card-panel-icon" :size="45">
              <Notebook />
            </el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">题目总数</div>
            <div class="card-panel-num">{{ animatedStatistics.questionCount }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleSetLineChartData('examAnswer')">
          <div class="card-panel-icon-wrapper icon-shopping">
            <el-icon class="card-panel-icon" :size="45">
              <Reading />
            </el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">答卷总数</div>
            <div class="card-panel-num">{{ animatedStatistics.examAnswerCount }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleSetLineChartData('studentAnswer')">
          <div class="card-panel-icon-wrapper icon-money">
            <el-icon class="card-panel-icon" :size="45">
              <EditPen />
            </el-icon>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">答题总数</div>
            <div class="card-panel-num">{{ animatedStatistics.studentAnswerCount }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 系统介绍卡片 -->
    <div class="intro-section">
      <div class="intro-card">
        <div class="header">
          <div class="title">系统介绍</div>
        </div>
        <div class="content">
          <div class="intro-text">
            <p><strong>离散数学组卷系统</strong>是一个专为离散数学教学设计的现代化在线教学平台。</p>
            <p>本系统提供强大的试卷管理、题目管理和在线考试功能，支持多种题型，包括单选题、多选题、判断题、填空题和简答题。</p>
            <p>教师可以通过系统轻松创建试卷、批改试卷，学生可以在线完成测试并获得及时反馈。</p>
            <p>系统支持AI辅助功能，提高出题效率及对已有题目优化。</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 答卷统计图表 -->
    <div class="chart-section">
      <div class="chart-card">
        <div class="chart-header">
          <div class="chart-title">{{ currentMonth }}月答卷统计</div>
        </div>
        <div class="chart-content">
          <div id="examChart" style="width: 100%; height: 350px;"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { 
  getSystemStatistics, 
  getExamCountByDay
} from '@/api/index';


// 获取当前月份
const currentMonth = new Date().getMonth() + 1;

// 统计数据
const statistics = reactive({
  paperCount: 0,
  questionCount: 0,
  examAnswerCount: 0,
  studentAnswerCount: 0
});

// 用于动画显示的统计数据
const animatedStatistics = reactive({
  paperCount: 1,
  questionCount: 1,
  examAnswerCount: 1,
  studentAnswerCount: 1
});

// Mock数据 - 当后端API尚未实现时使用
const useMockData = false;

// 数字动画效果
const animateNumbers = () => {
  // 动画持续时间（毫秒）
  const duration = 3000;
  // 动画帧数
  const frames = 60;
  // 帧间隔（毫秒）
  const frameInterval = duration / frames;
  
  // 每个数字每帧的增量
  const paperIncrement = (statistics.paperCount - 1) / frames;
  const questionIncrement = (statistics.questionCount - 1) / frames;
  const examAnswerIncrement = (statistics.examAnswerCount - 1) / frames;
  const studentAnswerIncrement = (statistics.studentAnswerCount - 1) / frames;
  
  // 当前帧
  let currentFrame = 0;
  
  // 重置动画起始值
  animatedStatistics.paperCount = 1;
  animatedStatistics.questionCount = 1;
  animatedStatistics.examAnswerCount = 1;
  animatedStatistics.studentAnswerCount = 1;
  
  // 创建动画间隔
  const animationInterval = setInterval(() => {
    currentFrame++;
    
    // 更新当前值
    animatedStatistics.paperCount = Math.round(1 + paperIncrement * currentFrame);
    animatedStatistics.questionCount = Math.round(1 + questionIncrement * currentFrame);
    animatedStatistics.examAnswerCount = Math.round(1 + examAnswerIncrement * currentFrame);
    animatedStatistics.studentAnswerCount = Math.round(1 + studentAnswerIncrement * currentFrame);
    
    // 当达到最后一帧时，设置为最终值并清除间隔
    if (currentFrame >= frames) {
      animatedStatistics.paperCount = statistics.paperCount;
      animatedStatistics.questionCount = statistics.questionCount;
      animatedStatistics.examAnswerCount = statistics.examAnswerCount;
      animatedStatistics.studentAnswerCount = statistics.studentAnswerCount;
      clearInterval(animationInterval);
    }
  }, frameInterval);
};

// 获取统计数据
const getStatistics = async () => {
  try {
    if (!useMockData) {
      const res = await getSystemStatistics();
      if (res.code === 200 && res.data) {
        statistics.paperCount = res.data.paperCount || 0;
        statistics.questionCount = res.data.questionCount || 0;
        statistics.examAnswerCount = res.data.examAnswerCount || 0;
        statistics.studentAnswerCount = res.data.studentAnswerCount || 0;
        
        // 确保所有值最小为1，防止动画出现问题
        if (statistics.paperCount < 1) statistics.paperCount = 1;
        if (statistics.questionCount < 1) statistics.questionCount = 1;
        if (statistics.examAnswerCount < 1) statistics.examAnswerCount = 1;
        if (statistics.studentAnswerCount < 1) statistics.studentAnswerCount = 1;
        
        // 启动动画
        animateNumbers();
      }
    } else {
      // 使用模拟数据
      statistics.paperCount = 356;
      statistics.questionCount = 183;
      statistics.examAnswerCount = 804;
      statistics.studentAnswerCount = 3524;
      
      // 启动动画
      animateNumbers();
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    // 使用模拟数据
    statistics.paperCount = 356;
    statistics.questionCount = 183;
    statistics.examAnswerCount = 804;
    statistics.studentAnswerCount = 3524;
    
    // 启动动画
    animateNumbers();
  }
};

// 处理图表点击事件
const handleSetLineChartData = (type) => {
  console.log('点击了统计卡片:', type);
};

// 用户答卷统计图表
let chartInstance = null;

// 初始化echarts
const initChart = async () => {
  const chartDom = document.getElementById('examChart');
  if (!chartDom) return;
  
  // 如果已有实例，先销毁
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  chartInstance = echarts.init(chartDom);
  
  try {
    let examData = [];
    
    if (!useMockData) {
      const res = await getExamCountByDay();
      if (res.code === 200 && res.data) {
        examData = res.data;
      }
    } else {
      // 模拟每日答卷次数数据
      examData = Array.from({ length: 31 }, () => Math.floor(Math.random() * 30));
    }
    
    // 获取当月天数
    const daysInMonth = new Date(new Date().getFullYear(), currentMonth, 0).getDate();
    
    const option = {
      title: {
        text: `${currentMonth}月每日答卷次数`,
        left: 'center',
        textStyle: {
          color: '#333',
          fontWeight: 'bold',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          shadowStyle: {
            color: 'rgba(0,0,0,0.05)'
          }
        },
        formatter: function(params) {
          return `${currentMonth}月${params[0].axisValue}日<br/>答卷次数：${params[0].data}`;
        },
        backgroundColor: 'rgba(255,255,255,0.9)',
        borderColor: '#eee',
        borderWidth: 1,
        textStyle: {
          color: '#333'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: Array.from({ length: daysInMonth }, (_, i) => i + 1),
        axisLabel: {
          formatter: '{value}日',
          color: '#666'
        },
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '答卷次数',
        nameLocation: 'end',
        nameGap: 15,
        nameTextStyle: {
          color: '#666',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#eee'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      series: [
        {
          name: '答卷次数',
          type: 'line',
          stack: 'Total',
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(80, 141, 255, 0.8)' },
              { offset: 1, color: 'rgba(80, 141, 255, 0.1)' }
            ])
          },
          emphasis: {
            focus: 'series'
          },
          data: examData.slice(0, daysInMonth),
          itemStyle: {
            color: '#508dff'
          },
          lineStyle: {
            width: 3
          },
          symbol: 'circle',
          symbolSize: 8,
          smooth: true
        }
      ]
    };
    
    option && chartInstance.setOption(option);
  } catch (error) {
    console.error('初始化图表失败:', error);
  }
};

// 页面初始化
const initData = async () => {
  await getStatistics();
  // 在DOM更新后初始化图表
  setTimeout(() => {
    initChart();
  }, 0);
};

// 窗口大小变化时重新渲染图表
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 自动刷新定时器
let timer = null;
const startAutoRefresh = () => {
  // 每5分钟刷新一次数据
  timer = setInterval(() => {
    getStatistics();
    initChart();
  }, 5 * 60 * 1000);
};

onMounted(() => {
  initData();
  startAutoRefresh();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  // 清除定时器和事件监听
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
  window.removeEventListener('resize', handleResize);
  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.panel-group {
  margin-bottom: 20px;

  .card-panel-col {
    margin-bottom: 20px;
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    border: 1px solid #ebeef5;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);

      .card-panel-icon-wrapper {
        color: #fff;
      }
      
      .icon-people {
        background-color: #40c9c6;
      }
      
      .icon-message {
        background-color: #36a3f7;
      }
      
      .icon-shopping {
        background-color: #f4516c;
      }
      
      .icon-money {
        background-color: #34bfa3;
      }
    }

    .card-panel-icon-wrapper {
      float: left;
      padding: 16px;
      transition: all 0.3s ease;
      border-radius: 6px;
      margin: 14px 0 0 14px;
    }

    .card-panel-icon {
      float: left;
      font-size: 48px;
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-shopping {
      color: #f4516c;
    }

    .icon-money {
      color: #34bfa3;
    }

    .card-panel-description {
      float: right;
      font-weight: bold;
      margin: 26px 26px 0 0;

      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 28px;
      }
    }
  }
}

// 系统介绍区域样式
.intro-section {
  margin-bottom: 20px;

  .intro-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #ebeef5;
    padding: 20px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
    }

    .header {
      margin-bottom: 15px;
      border-bottom: 1px solid #f0f0f0;
      padding-bottom: 10px;

      .title {
        font-size: 18px;
        font-weight: bold;
        position: relative;
        padding-left: 12px;
        
        &:before {
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          height: 100%;
          width: 4px;
          background: linear-gradient(to bottom, #36a3f7, #40c9c6);
          border-radius: 2px;
        }
      }
    }

    .content {
      .intro-text {
        font-size: 14px;
        line-height: 1.8;
        color: #333;

        p {
          margin-bottom: 10px;
          position: relative;
          padding-left: 18px;
          
          &:before {
            content: '•';
            position: absolute;
            left: 0;
            color: #36a3f7;
            font-size: 18px;
            line-height: 1.4;
          }
        }

        strong {
          font-weight: bold;
          color: #1890ff;
          position: relative;
          
          &:after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 100%;
            height: 4px;
            background-color: rgba(24, 144, 255, 0.2);
            border-radius: 2px;
          }
        }
      }
    }
  }
}

// 图表区域样式
.chart-section {
  .chart-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #ebeef5;
    padding: 20px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
    }

    .chart-header {
      margin-bottom: 20px;
      border-bottom: 1px solid #f0f0f0;
      padding-bottom: 10px;

      .chart-title {
        font-size: 18px;
        font-weight: bold;
        position: relative;
        padding-left: 12px;
        
        &:before {
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          height: 100%;
          width: 4px;
          background: linear-gradient(to bottom, #f4516c, #34bfa3);
          border-radius: 2px;
        }
      }
    }

    .chart-content {
      height: 350px;
      border-radius: 4px;
      overflow: hidden;
    }
  }
}

// 响应式布局调整
@media (max-width: 768px) {
  .panel-group {
    .card-panel-description {
      margin-right: 10px;
      
      .card-panel-text {
        font-size: 14px;
      }
      
      .card-panel-num {
        font-size: 24px;
      }
    }
  }
}
</style>